import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// 阈值定义（与activity-analysis保持一致）
const STEPS_STATIC_THRESHOLD = 20     // 10分钟内低于20步才算静止
const HR_STD_DEV_STEADY_THRESHOLD = 8.0 // 心率标准差低于8
const INTENSITY_PCT_MODERATE = 0.60   // 60% 心率储备
const INTENSITY_PCT_VIGOROUS = 0.80   // 80% 心率储备
const SKIN_TEMP_DELTA_SIGNIFICANT = 0.4 // 皮肤温度变化超过0.4°C

// MET值范围定义（极度保守以匹配实际合理消耗）
const MET_RANGES = {
  '睡眠行为': { min: 0.9, max: 1.0 },
  '静息行为': { min: 1.0, max: 1.02 }, // 极接近BMR
  '低强度活动': { min: 1.02, max: 1.2 }, // 极度降低
  '中强度活动': { min: 1.2, max: 1.8 }, // 极度降低
  '高强度活动': { min: 1.8, max: 3.0 }  // 极度降低
}

// 心率储备区间定义
const HRR_ZONES = {
  '睡眠行为': { min: -0.1, max: 0.1 },
  '静息行为': { min: 0.0, max: 0.2 },
  '低强度活动': { min: 0.2, max: 0.5 },
  '中强度活动': { min: 0.5, max: 0.7 },
  '高强度活动': { min: 0.7, max: 1.0 }
}

interface UserProfile {
  age: number
  gender: string | number
  height: number  // cm
  weight: number  // kg
  RHR: number     // 静息心率
  MHR: number     // 最大心率
  HRR: number     // 心率储备
}

interface DataWindow {
  timestamp: number
  steps_sum: number
  hr_mean: number
  hr_std_dev: number
  hr_max: number
  hr_min: number
  skin_temp_delta: number
  is_sleep_period: boolean
  user_profile: UserProfile
}

interface ActivityResult {
  classification_type: 'single' | 'composition'
  activity?: string
  duration_mins?: number
  met_value?: number
  calories?: number
  composition_mins?: {
    [key: string]: number
  }
}

interface DailyEnergyResult {
  date: string
  user_profile: UserProfile
  bmr: number           // 基础代谢率 (kcal)
  tef: number           // 食物热效应 (kcal)
  eepa: number          // 体力活动能量消耗 (kcal)
  tee: number           // 总能量消耗 (kcal)
  activity_breakdown: {
    [key: string]: {
      duration_mins: number
      avg_met: number
      calories: number
    }
  }
  daily_summary: {
    total_activity_mins: number
    avg_heart_rate: number
    total_steps: number
    active_calories: number
    rest_calories: number
  }
}

// 计算基础代谢率 (BMR) - 使用Mifflin-St Jeor公式
function calculateBMR(userProfile: UserProfile): number {
  const { age, gender, height, weight } = userProfile
  
  // 数据验证
  if (height <= 0 || weight <= 0 || age <= 0) {
    console.warn(`BMR计算数据异常: age=${age}, height=${height}, weight=${weight}, gender=${gender}`)
    // 使用默认值进行计算
    const defaultHeight = height > 0 ? height : 170
    const defaultWeight = weight > 0 ? weight : 70
    const defaultAge = age > 0 ? age : 30
    
    // 判断性别：1为男性，2为女性，其他默认为男性
    const isMale = gender === 1 || gender === '1'
    
    let bmr: number
    if (isMale) {
      bmr = (10 * defaultWeight) + (6.25 * defaultHeight) - (5 * defaultAge) + 5
    } else if (gender === 2 || gender === '2') {
      bmr = (10 * defaultWeight) + (6.25 * defaultHeight) - (5 * defaultAge) - 161
    } else {
      // 未知性别，默认使用男性公式
      bmr = (10 * defaultWeight) + (6.25 * defaultHeight) - (5 * defaultAge) + 5
    }
    
    return Math.round(bmr * 10) / 10
  }

  let bmr: number
  // 判断性别：1为男性，2为女性，其他默认为男性
  const isMale = gender === 1 || gender === '1'
  
  if (isMale) {
    // 男性: BMR = (10 × 体重kg) + (6.25 × 身高cm) - (5 × 年龄岁) + 5
    bmr = (10 * weight) + (6.25 * height) - (5 * age) + 5
  } else if (gender === 2 || gender === '2') {
    // 女性: BMR = (10 × 体重kg) + (6.25 × 身高cm) - (5 × 年龄岁) - 161
    bmr = (10 * weight) + (6.25 * height) - (5 * age) - 161
  } else {
    // 未知性别，默认使用男性公式
    bmr = (10 * weight) + (6.25 * height) - (5 * age) + 5
  }
  
  return Math.round(bmr * 10) / 10 // 保留一位小数
}

// 计算食物热效应 (TEF) - 基于BMR和EEPA的10%
function calculateTEF(bmr: number, eepa: number): number {
  // TEF通常占总摄入的8-10%，这里简化为(BMR + EEPA)的10%
  // 这个近似假设用户摄入与消耗基本平衡
  const tef = (bmr + eepa) * 0.1
  return Math.round(tef * 10) / 10
}

// 动态MET值计算函数（与activity-analysis完全一致）
function calculateDynamicMET(dataWindow: DataWindow, activityType: string): number {
  // 获取该活动类型的MET范围和心率储备范围
  const metRange = MET_RANGES[activityType as keyof typeof MET_RANGES]
  const hrrZone = HRR_ZONES[activityType as keyof typeof HRR_ZONES]
  
  if (!metRange || !hrrZone) {
    // 如果找不到对应范围，返回默认MET值
    return MET_RANGES['静息行为'].min
  }

  // 计算当前心率储备百分比
  const currentIntensityPct = (dataWindow.hr_mean - dataWindow.user_profile.RHR) / dataWindow.user_profile.HRR
  
  // 计算在所属强度区间的进度百分比
  const zoneWidth = hrrZone.max - hrrZone.min
  if (zoneWidth <= 0) {
    return metRange.min // 如果区间宽度为0，返回最小MET值
  }

  let progressInZone = (currentIntensityPct - hrrZone.min) / zoneWidth
  // 确保百分比在 [0, 1] 范围内
  progressInZone = Math.max(0, Math.min(1, progressInZone))

  // 根据进度百分比在MET范围内进行线性插值
  const metRangeWidth = metRange.max - metRange.min
  const dynamicMET = metRange.min + (metRangeWidth * progressInZone)

  // 可选：根据步数进行微调
  // 如果步数特别高，给予小幅奖励加成
  let adjustedMET = dynamicMET
  if (activityType !== '睡眠行为' && activityType !== '静息行为') {
    const avgStepsForActivity = getAverageStepsForActivity(activityType)
    if (dataWindow.steps_sum > avgStepsForActivity * 1.2) {
      adjustedMET = dynamicMET * 1.05 // 增加5%的MET值
    }
  }

  return Math.round(adjustedMET * 100) / 100 // 保留两位小数
}

// 获取各活动类型的平均步数（基于经验数据）
function getAverageStepsForActivity(activityType: string): number {
  const averageSteps = {
    '睡眠行为': 0,
    '静息行为': 20,
    '低强度活动': 300,
    '中强度活动': 800,
    '高强度活动': 1200
  }
  return averageSteps[activityType as keyof typeof averageSteps] || 100
}

// 计算卡路里消耗
function calculateCalories(metValue: number, weightKg: number, durationMins: number): number {
  const calories = metValue * 3.5 * weightKg / 200 * durationMins
  return Math.round(calories * 10) / 10
}

// 获取用户基本信息
async function getUserProfile(userId: string): Promise<UserProfile> {
  try {
    const user = await prisma.smoke_user.findUnique({
      where: { id: parseInt(userId) },
      select: {
        birthday: true,
        gender: true,
        height: true,
        weight: true
      }
    })

    if (!user) {
      throw new Error('用户不存在')
    }

    // 计算年龄
    let age = 30 // 默认年龄
    if (user.birthday) {
      try {
        const birthDate = new Date(user.birthday)
        const today = new Date()
        let calculatedAge = today.getFullYear() - birthDate.getFullYear()
        const monthDiff = today.getMonth() - birthDate.getMonth()
        
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
          calculatedAge--
        }
        
        if (calculatedAge > 0 && calculatedAge < 120) {
          age = calculatedAge
        }
      } catch (error) {
        console.error('计算年龄失败:', error)
      }
    }

    // 获取身高体重
    const height = user.height ? parseFloat(user.height) : 170
    const weight = user.weight ? parseFloat(user.weight) : 70

    // 计算心率相关指标
    const MHR = 220 - age // 最大心率估算
    const RHR = await calculateRestingHeartRate(userId) // 静息心率
    const HRR = MHR - RHR // 心率储备

    return {
      age,
      gender: user.gender || 'male',
      height,
      weight,
      RHR,
      MHR,
      HRR
    }
  } catch (error) {
    console.error('获取用户档案失败:', error)
    // 返回默认值
    return {
      age: 30,
      gender: 'male',
      height: 170,
      weight: 70,
      RHR: 60,
      MHR: 190,
      HRR: 130
    }
  }
}

// 主分类函数（与activity-analysis完全一致）
async function classifyActivityRefined(dataWindow: DataWindow, userWeight: number): Promise<ActivityResult> {
  // 阶段一：处理无活动状态 (睡眠或静息)
  if (dataWindow.steps_sum < STEPS_STATIC_THRESHOLD) {
    // 区分睡眠和静息
    let activityType: string
    if (dataWindow.is_sleep_period && dataWindow.hr_mean < (dataWindow.user_profile.RHR + 5)) {
      activityType = '睡眠行为'
    } else {
      activityType = '静息行为'
    }

    const dynamicMET = calculateDynamicMET(dataWindow, activityType)
    const calories = calculateCalories(dynamicMET, userWeight, 10)

    return {
      classification_type: 'single',
      activity: activityType,
      duration_mins: 10,
      met_value: dynamicMET,
      calories: calories
    }
  }

  // 阶段二：区分活动模式 (稳态 vs. 混合)
  const IS_STEADY_STATE = dataWindow.hr_std_dev < HR_STD_DEV_STEADY_THRESHOLD

  if (IS_STEADY_STATE) {
    return handleSteadyStateActivity(dataWindow, userWeight)
  } else {
    return handleMixedActivity(dataWindow, userWeight)
  }
}

// 处理稳态活动
function handleSteadyStateActivity(dataWindow: DataWindow, userWeight: number): ActivityResult {
  const intensity_pct = (dataWindow.hr_mean - dataWindow.user_profile.RHR) / dataWindow.user_profile.HRR
  
  let activity_type = ''

  if (intensity_pct >= INTENSITY_PCT_VIGOROUS) {
    // 高强度需要皮肤温度作为旁证
    if (dataWindow.skin_temp_delta > SKIN_TEMP_DELTA_SIGNIFICANT) {
      activity_type = '高强度活动'
    } else {
      activity_type = '中强度活动' // 证据不足，保守降级
    }
  } else if (intensity_pct >= INTENSITY_PCT_MODERATE) {
    activity_type = '中强度活动'
  } else {
    activity_type = '低强度活动'
  }

  const dynamicMET = calculateDynamicMET(dataWindow, activity_type)
  const calories = calculateCalories(dynamicMET, userWeight, 10)

  return {
    classification_type: 'single',
    activity: activity_type,
    duration_mins: 10,
    met_value: dynamicMET,
    calories: calories
  }
}

// 处理混合活动
function handleMixedActivity(dataWindow: DataWindow, userWeight: number): ActivityResult {
  // 计算峰值活动的强度
  const peak_intensity_pct = (dataWindow.hr_max - dataWindow.user_profile.RHR) / dataWindow.user_profile.HRR

  // 估算峰值活动的时间
  let peak_activity_mins = 0
  const hr_range = dataWindow.hr_max - dataWindow.hr_min
  
  if (hr_range > 5) {
    peak_activity_mins = 10 * (dataWindow.hr_mean - dataWindow.hr_min) / hr_range
    peak_activity_mins = Math.max(0, Math.min(10, peak_activity_mins))
  }

  const base_activity_mins = 10 - peak_activity_mins

  // 构建时间分配结果
  const composition = {
    '睡眠行为': 0,
    '静息行为': 0,
    '低强度活动': 0,
    '中强度活动': 0,
    '高强度活动': 0
  }

  // 将峰值时间分配到对应的强度类别
  let peakActivityType = '低强度活动'
  if (peak_intensity_pct >= INTENSITY_PCT_VIGOROUS) {
    peakActivityType = '高强度活动'
    composition['高强度活动'] = peak_activity_mins
  } else if (peak_intensity_pct >= INTENSITY_PCT_MODERATE) {
    peakActivityType = '中强度活动'
    composition['中强度活动'] = peak_activity_mins
  } else {
    composition['低强度活动'] = peak_activity_mins
  }

  // 将基础活动时间分配到低强度类别
  composition['低强度活动'] += base_activity_mins

  // 计算混合活动的总卡路里（各部分卡路里之和）
  let totalCalories = 0
  Object.entries(composition).forEach(([activityType, duration]) => {
    if (duration > 0) {
      // 为混合活动创建临时数据窗口来计算MET
      const tempDataWindow = { ...dataWindow }
      if (activityType === peakActivityType) {
        // 峰值活动使用原始心率数据
        tempDataWindow.hr_mean = dataWindow.hr_max
      } else {
        // 基础活动使用较低的心率
        tempDataWindow.hr_mean = Math.round((dataWindow.hr_min + dataWindow.user_profile.RHR) / 2)
      }
      
      const activityMET = calculateDynamicMET(tempDataWindow, activityType)
      const activityCalories = calculateCalories(activityMET, userWeight, duration)
      totalCalories += activityCalories
    }
  })

  return {
    classification_type: 'composition',
    composition_mins: composition,
    calories: Math.round(totalCalories * 10) / 10
  }
}

// 计算静息心率
async function calculateRestingHeartRate(userId: string): Promise<number> {
  try {
    // 获取最近7天的心率数据，计算静息心率
    const sevenDaysAgo = new Date()
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
    const startTimestamp = BigInt(sevenDaysAgo.getTime())
    const endTimestamp = BigInt(Date.now())

    const heartRateData = await prisma.yh_logs.findMany({
      where: {
        user_id: parseInt(userId),
        type: 'heart_rate',
        timestamp: {
          gte: startTimestamp,
          lt: endTimestamp
        },
        deleted_at: 0
      },
      select: {
        data: true
      },
      orderBy: {
        timestamp: 'desc'
      },
      take: 1000 // 限制数据量
    })

    const heartRates: number[] = []
    
    heartRateData.forEach(log => {
      try {
        const data = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
        const heartRate = parseInt(data.heartRate) || parseInt(data.onceHeartValue) || 0
        if (heartRate > 40 && heartRate < 200) {
          heartRates.push(heartRate)
        }
      } catch (error) {
        // 忽略解析错误的数据
      }
    })

    if (heartRates.length > 0) {
      // 使用最低的20%心率值的平均值作为静息心率
      heartRates.sort((a, b) => a - b)
      const bottomCount = Math.max(1, Math.floor(heartRates.length * 0.2))
      const bottomHeartRates = heartRates.slice(0, bottomCount)
      const rhr = bottomHeartRates.reduce((sum, hr) => sum + hr, 0) / bottomHeartRates.length
      return Math.round(rhr)
    }
    
    return 60 // 默认静息心率
  } catch (error) {
    console.error('计算静息心率失败:', error)
    return 60
  }
}

// 聚合10分钟窗口数据（与activity-analysis完全一致）
async function aggregateDataWindows(userId: string, startDate: string, endDate: string): Promise<DataWindow[]> {
  try {
    const startTimestamp = BigInt(new Date(startDate).getTime())
    const endTimestamp = BigInt(new Date(endDate).getTime())

    // 获取所有相关数据
    const [heartRateLogs, stepLogs, temperatureLogs] = await Promise.all([
      prisma.yh_logs.findMany({
        where: {
          user_id: parseInt(userId),
          type: 'heart_rate',
          timestamp: { gte: startTimestamp, lt: endTimestamp },
          deleted_at: 0
        },
        orderBy: { timestamp: 'asc' }
      }),
      prisma.yh_logs.findMany({
        where: {
          user_id: parseInt(userId),
          type: 'step',
          timestamp: { gte: startTimestamp, lt: endTimestamp },
          deleted_at: 0
        },
        orderBy: { timestamp: 'asc' }
      }),
      prisma.yh_logs.findMany({
        where: {
          user_id: parseInt(userId),
          type: 'temperature',
          timestamp: { gte: startTimestamp, lt: endTimestamp },
          deleted_at: 0
        },
        orderBy: { timestamp: 'asc' }
      })
    ])

    // 获取用户生理基准
    const userProfile = await getUserProfile(userId)

    // 创建10分钟时间窗口
    const windows: DataWindow[] = []
    const windowSizeMs = 10 * 60 * 1000 // 10分钟

    for (let windowStart = startTimestamp; windowStart < endTimestamp; windowStart = BigInt(Number(windowStart) + windowSizeMs)) {
      const windowEnd = BigInt(Number(windowStart) + windowSizeMs)
      
      // 聚合该窗口内的数据
      const windowData = aggregateWindowData(
        windowStart,
        windowEnd,
        heartRateLogs,
        stepLogs,
        temperatureLogs,
        userProfile
      )

      if (windowData) {
        windows.push(windowData)
      }
    }

    return windows
  } catch (error) {
    console.error('聚合数据窗口失败:', error)
    return []
  }
}

// 聚合单个窗口的数据（与activity-analysis完全一致）
function aggregateWindowData(
  windowStart: bigint,
  windowEnd: bigint,
  heartRateLogs: any[],
  stepLogs: any[],
  temperatureLogs: any[],
  userProfile: UserProfile
): DataWindow | null {
  try {
    // 筛选窗口内的数据
    const windowHeartRates: number[] = []
    const windowSteps: number[] = []
    const windowTemperatures: number[] = []

    // 处理心率数据
    heartRateLogs.forEach(log => {
      if (log.timestamp >= windowStart && log.timestamp < windowEnd) {
        try {
          const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
          // 心率数据可能存储在 heartRate 或 onceHeartValue 字段中
          const heartRate = parseInt(logData.heartRate) || parseInt(logData.onceHeartValue) || 0
          if (heartRate > 30 && heartRate < 220) {
            windowHeartRates.push(heartRate)
          }
        } catch (error) {
          console.error('解析心率数据失败:', error)
        }
      }
    })

    // 处理步数数据
    stepLogs.forEach(log => {
      if (log.timestamp >= windowStart && log.timestamp < windowEnd) {
        try {
          const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
          const steps = parseInt(logData.detailMinterStep) || 0
          if (steps > 0) {
            windowSteps.push(steps)
          }
        } catch (error) {
          console.error('解析步数数据失败:', error)
        }
      }
    })

    // 处理温度数据
    temperatureLogs.forEach(log => {
      if (log.timestamp >= windowStart && log.timestamp < windowEnd) {
        try {
          const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
          const temperature = parseFloat(logData.temperature) || 0
          if (temperature > 30 && temperature < 45) {
            windowTemperatures.push(temperature)
          }
        } catch (error) {
          console.error('解析温度数据失败:', error)
        }
      }
    })

    // 如果没有足够的数据，跳过该窗口
    if (windowHeartRates.length === 0) {
      return null
    }

    // 计算聚合指标
    const steps_sum = windowSteps.reduce((sum, steps) => sum + steps, 0)
    const hr_mean = windowHeartRates.reduce((sum, hr) => sum + hr, 0) / windowHeartRates.length
    const hr_max = Math.max(...windowHeartRates)
    const hr_min = Math.min(...windowHeartRates)
    
    // 计算心率标准差
    const hr_variance = windowHeartRates.reduce((sum, hr) => sum + Math.pow(hr - hr_mean, 2), 0) / windowHeartRates.length
    const hr_std_dev = Math.sqrt(hr_variance)

    // 计算皮肤温度变化
    let skin_temp_delta = 0
    if (windowTemperatures.length > 1) {
      const temp_max = Math.max(...windowTemperatures)
      const temp_min = Math.min(...windowTemperatures)
      skin_temp_delta = temp_max - temp_min
    }

    // 判断是否为睡眠时段（22:00-06:00）
    const windowTime = new Date(Number(windowStart))
    const hour = windowTime.getHours()
    const is_sleep_period = hour >= 22 || hour <= 6

    return {
      timestamp: Number(windowStart),
      steps_sum,
      hr_mean: Math.round(hr_mean),
      hr_std_dev: Math.round(hr_std_dev * 10) / 10, // 保留1位小数
      hr_max,
      hr_min,
      skin_temp_delta: Math.round(skin_temp_delta * 10) / 10, // 保留1位小数
      is_sleep_period,
      user_profile: userProfile
    }
  } catch (error) {
    console.error('聚合窗口数据失败:', error)
    return null
  }
}

// 获取一天的活动数据并计算EEPA（重构为使用新的数据聚合方式）
async function calculateDailyEEPA(userId: string, targetDate: string, userProfile: UserProfile): Promise<{
  eepa: number,
  activityBreakdown: any,
  dailySummary: any
}> {
  try {
    // 构建查询时间范围（目标日期的00:00:00到23:59:59）
    const startDate = targetDate + 'T00:00:00'
    const endDate = targetDate + 'T23:59:59'

    // 使用新的数据聚合方式
    const dataWindows = await aggregateDataWindows(userId, startDate, endDate)

    // 初始化活动统计
    const activityBreakdown = {
      '睡眠行为': { duration_mins: 0, avg_met: 0, calories: 0 },
      '静息行为': { duration_mins: 0, avg_met: 0, calories: 0 },
      '低强度活动': { duration_mins: 0, avg_met: 0, calories: 0 },
      '中强度活动': { duration_mins: 0, avg_met: 0, calories: 0 },
      '高强度活动': { duration_mins: 0, avg_met: 0, calories: 0 }
    }

    let totalSteps = 0
    let totalHeartRateSum = 0
    let heartRateCount = 0
    let totalEEPA = 0

    // 对每个窗口进行活动分类并计算卡路里
    for (const dataWindow of dataWindows) {
      const classification = await classifyActivityRefined(dataWindow, userProfile.weight)
      
      totalSteps += dataWindow.steps_sum
      totalHeartRateSum += dataWindow.hr_mean
      heartRateCount++

      if (classification.classification_type === 'single') {
        // 单一活动分类
        const activityType = classification.activity!
        const calories = classification.calories!
        
        activityBreakdown[activityType as keyof typeof activityBreakdown].duration_mins += 10
        activityBreakdown[activityType as keyof typeof activityBreakdown].calories += calories
        totalEEPA += calories
      } else {
        // 混合活动分类
        const compositionMins = classification.composition_mins!
        const totalCalories = classification.calories!
        
        Object.entries(compositionMins).forEach(([activityType, duration]) => {
          if (duration > 0) {
            // 按比例分配卡路里
            const proportionalCalories = (duration / 10) * totalCalories
            activityBreakdown[activityType as keyof typeof activityBreakdown].duration_mins += duration
            activityBreakdown[activityType as keyof typeof activityBreakdown].calories += proportionalCalories
          }
        })
        
        totalEEPA += totalCalories
      }
    }

    // 计算各活动类型的平均MET值
    Object.keys(activityBreakdown).forEach(activityType => {
      const breakdown = activityBreakdown[activityType as keyof typeof activityBreakdown]
      if (breakdown.duration_mins > 0) {
        // 根据总卡路里和时长反推平均MET值
        const avgMET = (breakdown.calories * 200) / (3.5 * userProfile.weight * breakdown.duration_mins)
        breakdown.avg_met = Math.round(avgMET * 100) / 100
      }
    })

    // 计算日总结
    const totalActivityMins = Object.values(activityBreakdown).reduce((sum, activity) => sum + activity.duration_mins, 0)
    const avgHeartRate = heartRateCount > 0 ? Math.round(totalHeartRateSum / heartRateCount) : userProfile.RHR
    
    // 计算活动卡路里（排除睡眠和静息）
    const activeCalories = activityBreakdown['低强度活动'].calories + 
                          activityBreakdown['中强度活动'].calories + 
                          activityBreakdown['高强度活动'].calories
    
    const restCalories = activityBreakdown['睡眠行为'].calories + 
                        activityBreakdown['静息行为'].calories

    const dailySummary = {
      total_activity_mins: totalActivityMins,
      avg_heart_rate: avgHeartRate,
      total_steps: totalSteps,
      active_calories: Math.round(activeCalories * 10) / 10,
      rest_calories: Math.round(restCalories * 10) / 10
    }

    return {
      eepa: Math.round(totalEEPA * 10) / 10,
      activityBreakdown,
      dailySummary
    }
  } catch (error) {
    console.error('计算EEPA失败:', error)
    return {
      eepa: 0,
      activityBreakdown: {
        '睡眠行为': { duration_mins: 0, avg_met: 0, calories: 0 },
        '静息行为': { duration_mins: 0, avg_met: 0, calories: 0 },
        '低强度活动': { duration_mins: 0, avg_met: 0, calories: 0 },
        '中强度活动': { duration_mins: 0, avg_met: 0, calories: 0 },
        '高强度活动': { duration_mins: 0, avg_met: 0, calories: 0 }
      },
      dailySummary: {
        total_activity_mins: 0,
        avg_heart_rate: 60,
        total_steps: 0,
        active_calories: 0,
        rest_calories: 0
      }
    }
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')
    const date = searchParams.get('date') // 格式: YYYY-MM-DD

    if (!userId || !date) {
      return NextResponse.json(
        { error: '缺少必要参数: userId, date' },
        { status: 400 }
      )
    }

    // 验证日期格式
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/
    if (!dateRegex.test(date)) {
      return NextResponse.json(
        { error: '日期格式错误，应为 YYYY-MM-DD' },
        { status: 400 }
      )
    }

    // 获取用户档案
    const userProfile = await getUserProfile(userId)

    // 计算BMR（基础代谢率）
    const bmr = calculateBMR(userProfile)

    // 计算EEPA（体力活动能量消耗）
    const { eepa, activityBreakdown, dailySummary } = await calculateDailyEEPA(userId, date, userProfile)

    // 计算TEF（食物热效应）
    const tef = calculateTEF(bmr, eepa)

    // 计算TEE（总能量消耗）
    const tee = bmr + tef + eepa

    const result: DailyEnergyResult = {
      date,
      user_profile: userProfile,
      bmr: bmr,
      tef: tef,
      eepa: eepa,
      tee: Math.round(tee * 10) / 10,
      activity_breakdown: activityBreakdown,
      daily_summary: dailySummary
    }

    return NextResponse.json({
      success: true,
      data: result,
      message: '每日能量消耗计算成功'
    })

  } catch (error) {
    console.error('Daily energy calculation error:', error)
    return NextResponse.json({
      success: false,
      error: 'Calculation failed',
      message: '每日能量消耗计算失败'
    }, { status: 500 })
  }
}
